var chatListener = null;
var memberListListener = null;
var messageListener = null;
var pvtMessageListener = null;
var messageLimit = 15;
            
/*
 * loadChat: function to handle loading of a chat
 */
function loadChat(chatid){
        var lastmsgid = $("#lastmsgid").val();

        // Set up the request
        var payload = "chatid=" + encodeURI(chatid) + "&lastmsgid=" + encodeURI(lastmsgid);
        payload += "&doAction=";
        
        // If this is the initial signon (i.e., no comments in the chat contents
        // box), send a 'loadChat' request; otherwise, check for new messages.
        if(document.getElementById("chat_contents").childNodes.length==0) {
            payload += "loadChat";
        } else {
            payload += "getNewMessages";
        }

	$.ajax({
            type: 'GET',
            url: '_eventManager.jsp',
            data: payload,
            success: function(data){ loadChatData(data); }
        });
}
 
// function to handle return from chatloader servlet
function loadChatData(data) {
 	var cc = $("#chat_contents").get(0);
	var chatid = $("#chatid").val();
	var userid = $("#userid").val();
		
	   if(data) {
             if (data!="false" && chatid > 0) {
                cc.innerHTML += data;
                cc.lastChild.scrollIntoView(true);
                cc.scrollTop = cc.scrollHeight;

                var lastmsgid = $("#lastmsgid").get(0);
                if (cc.childNodes.length > 0 ) {
                    lastmsgid.value = cc.lastChild.getAttribute("id");
                }

                // Clear out the comment field & drop old messages
                dropOldMessages(cc);
            } else {
                signOff(userid);
                cc.innerHTML = "<p style='color: #990000'><b>The chat has been closed</b></p>";
            }
	   }
}  
         
// function to handle adding to a chat
function addComment(){
    // Update the hidden action field in the comment form
    $("#doAction").val("addComment");

    // Get the user's comment
    var comment = $("#comment").val();
    if(comment=="") {
        comment = document.getElementById("comment").innerHTML;
    }

    if(comment != "") {
        // Get the contents of the comment form
        var payload = $("#commentfrm").serialize();

        // Update the user's status on the server and the GUI  
        $.ajax({
            type: 'POST',
            url: '_eventManager.jsp',
            data: payload,
            success: function(data){ loadChatData(data); }
        });

        // Clear the comment field
        $("#comment").val("");
    } else {
        alert ("Please type a comment.");
    }
}
            
// function to handle signoff
function signOff(){
    // Prepare to signoff
    $("#doAction").val("signoff");
 
    // Stop the chat listeners
    stopListeners();
           
    // Set up the request
    if($("#chatid").val() > 0) {
        var payload = "doAction=" + encodeURI($("#doAction").val());
        payload += "&userid=" + encodeURI($("#userid").val());
        payload += "&chatid=" + encodeURI($("#chatid").val());

        // Sign off the user
        $.ajax({
            type: 'POST',
            url: '_userManager.jsp',
            data: payload,
            success: function(data){ exitChat(data); }
        });

        // Set the chat's ID to zero
        $("#chatid").val(0);
    }
}

// Shut down the chat GUI
function exitChat(data) {
    $("#commentfrm").css('display', 'none');
    $("#membersblock").css('display', 'none');
    $("#pvtmsgfrm").css('display', 'none');
    $("#pvtmessages").css('display', 'none');
    $("#soff").css('display', 'none');

    var cc = $("#chat_contents").get(0);
    cc.innerHTML = "<p style=\"color: #009900;\"><strong>Thank you for participating!</strong></p>";
    cc.innerHTML += "<p>This window will close in a moment...</p>";

    $("pvtmessage_contents").html("");
    setTimeout("window.close()", 3000);
}
           
// function to handle signon
function signOn(chatID, userID){
    $("#doAction").val("signon");

    // Hide the private message form
    $("#pvtmsgfrm").css('display','none');

    // Set up the request
    var payload = "doAction=" + encodeURI($("#doAction").val());
    payload += "&userid=" + encodeURI(userID);
    payload += "&chatid=" + encodeURI(chatID);

    // User sign in
    $.ajax({
            type: 'POST',
            url: '_userManager.jsp',
            data: payload,
            success: function(data){ openWindow(data); }
    });

    // Load the chat members & contents
    updateMembers(chatID);
    loadChat(chatID);
}

function openWindow(data) {
    var chatid = $("#chatid").val();
    var userid = $("#userid").val();
 
    // If we have a legit chat, start polling
    if(chatid > 0) {
        startListeners();
    }

    // Set up the request to get the chat's owner
    var payload = "doAction=getOwner";
    payload += "&userid=" + encodeURI(userid);
    payload += "&chatid=" + encodeURI(chatid);

    $.ajax({
            type: 'GET',
            url: '_userManager.jsp',
            data: payload,
            success: function(data){ getOwner(data); }
    });           
}

function getOwner(data) {
    var owner = data;
    var userid = $("#userid").val();
 
    if(userid == owner) {
        $("#endchat").css('display','');
    } else {
        $("#endchat").css('display','none');
    }
}

// function to display the private message form
function showPvtMsg(targetid, username) {
                var cid_node = document.getElementById("chatid");
                var cid = cid_node.value;
                var uid_node = document.getElementById("userid");
                var uid = uid_node.value;
                var target_node = document.getElementById("pvttargetid");
                var label_node = document.getElementById("pvtmsgheader");

                //if(targetid != uid) {
                    document.getElementById("pvtchatid").value = cid;
                    target_node.value = targetid;
                    label_node.innerHTML = "Send Private Message to " + username;
                    toggleWindow(document.getElementById("membersblock"));
                //}
            }

// function to handle ending a chat
function endChat(){
    var userid = $("#userid").val();
    var chatid = $("#chatid").val();
    var payload = "userid=" + userid + "&chatid=" + chatid;

        // Sign off the user
        $.ajax({
            type: 'GET',
            url: '../servlet/chatManagers.endChat',
            data: payload
        });

    signOff(userid);
}


// functions to handle updating the list of participants in a chat
function updateMembers(chatid) {
    // Set up the request to get the chat's owner
    var payload = "doAction=getAllChatters";
    payload += "&chatid=" + encodeURI(chatid);
            
    $.ajax({
            type: 'GET',
            url: '_eventManager.jsp',
            data: payload,
            success: function(data){ loadMemberList(data); }
    });           
}

function loadMemberList(data) {
     $("#members").html(data);
}

// functions to handle private messages
            function sendPvtMsg() {
                var comment_node = document.getElementById("pvtcomment");
                var comment = comment_node.value;
                if(comment != "") {
                    dojo.io.bind({
                    url: "_privateMessage.jsp",
                    formNode: document.getElementById("pvtmsgfrm")
                    });
                    comment_node.value = "";
                } else {
                    alert ("Please type a message.");
                }
            }

            function getPvtMessages() {
                var cid = document.getElementById("chatid").value;
                var uid = document.getElementById("userid").value;
                dojo.io.bind({
                url: "_eventManager.jsp",
                load: loadPvtMessages,
                content: {"method": "getPrivateMessages", "cid": cid, "uid": uid}
                });
            }

            function loadPvtMessages(type, data, evt) {
                var pc = document.getElementById("pvtmessage_contents");
                if (!data) {
                    pc.style.display = '';
                } else {
                    pc.innerHTML = pc.innerHTML + data;
                    pc.style.display = '';
                    pc.scrollTop = pc.scrollHeight;
                }
            }

function dropOldMessages(ccNode) {
    while(ccNode.childNodes.length > messageLimit) {
        ccNode.removeChild(ccNode.firstChild);
    }
}

// function to toggle between members and send private msg windows
function toggleWindow(node) {
    node.style.display='none';
    if (node == document.getElementById("membersblock")) {
        $("#pvtmsgfrm").css('display','');
    } else {
        $("#membersblock").css('display','');
    }
}

// Listener functions
function runListeners() {
    loadChat($("#chatid").val());
    updateMembers($("#chatid").val());
    //getPvtMessages();
}

function startListeners() {
    chatListener = setInterval('runListeners()', 4000);
}

function stopListeners() {
    clearInterval(chatListener);
    chatListener = null;
}

// Cursor functions
function setCursor() { document.body.style.cursor='pointer'; }
function resetCursor() { document.body.style.cursor='default'; }